from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

import jinja2

import models
import util


TMPL_LOADER = jinja2.FileSystemLoader('templates')
TMPL_ENV = jinja2.Environment(loader=TMPL_LOADER)


class Top50Handler(webapp.RequestHandler):

    @util.cache_control
    @util.memcache_get
    def get(self):
        query = models.ProjectModel.all().order('-' + self.property_repr).fetch(50)
        query = list(query)
        on_py3k = sum(x.py3k_status in models.ProjectModel.PY3K_GOOD
                      for x in query)
        template = TMPL_ENV.get_template('top50.html')
        self.response.out.write(template.render(on_py3k=on_py3k,
                                                projects=query,
                                                property_name=self.property_str))


class DownloadRateHandler(Top50Handler):

    property_repr = 'download_rate'
    property_str = 'downloads per day'


class DownloadTotalHandler(Top50Handler):

    property_repr = 'download_total'
    property_str = 'download total'


app = webapp.WSGIApplication([('/', DownloadRateHandler),
                              ('/download_total', DownloadTotalHandler),
                              ('/download_rate', DownloadRateHandler),
    #                          ('/pypi/(.+)', XXX)
                             ],
                             debug=util.DEBUG)
